<?php

namespace App\Repository\Orders;

use App\Models\Orders\OrdersUserModel as model;
use App\Repository\BaseRepository;

class OrdersUserRepository extends BaseRepository
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new model();
        parent::__construct();
    }

    public function index($where)
    {
        $cron = $where;
        $cron['order'] = ['orderby' => 'orders_user.id', 'orderdir' => 'desc'];
        $data = $this->search($this->model, $cron);
        return $data;
    }

    public function getManyOrders($where, $whereWith)
    {
        // 分页 + 条件
        $model = $this->model;
        if (!empty($where['where'])) {
            $model = $model->where($where['where']);
        }
        if (!empty($where['whereors'])) {
            $alls = $where['whereors'];
            foreach ($alls as $keys => $a) {
                $model = $model->where(function ($query) use ($a) {
                    $query->where($a['where'])->orWhere($a['whereor']);
                });
            }
        }
        if (isset($where['between']) && $where['between']) {
            foreach ($where['between'] as $k => $v)
                $model = $model->whereBetween($k, $v);
        }
        if (isset($where['like']) && $where['like']) //此数据可以配配用户串
        {
            $model = $model->where(function ($query) use ($where) {
                foreach ($where['like'] as $lk => $lv)
                    $query->where($lk, 'like', '%' . $lv . '%');
            });
        }


        $model = $model->with('hasOrders')->whereHas('hasOrders', function ($q) use ($whereWith) {
            if (!empty($whereWith['where'])) {
                $q->where($whereWith['where']);
                // foreach ($whereWith as $key => $v) {
                //   $q->where($key, '=', $v);
                // }
            }
            if (isset($whereWith['between']) && $whereWith['between']) {
                foreach ($whereWith['between'] as $k => $v)
                    $q->whereBetween($k, $v);
            }
            if (isset($where['like']) && $where['like']) //此数据可以配配用户串
            {
                $q->where(function ($query) use ($where) {
                    foreach ($where['like'] as $lk => $lv)
                        $query->where($lk, 'like', '%' . $lv . '%');
                });
            }
            if (!empty($whereWith['whereors'])) {
                $alls = $whereWith['whereors'];
                foreach ($alls as $keys => $a) {
                    $q->where(function ($query) use ($a) {
                        $query->where($a['where'])->orWhere($a['whereor']);
                    });
                }
            }
        });
        $count = $model->count();
        if (isset($where['limit']) && $where['limit']) {
            $model = $model->skip($where['limit']['start'])->take($where['limit']['number']);
        }

        $data = $model->get();
        if ($data) {
            foreach ($data as $key => &$v) {
                $has = json_decode(json_encode($v['hasOrders']), true);
                $v['nums'] = count($has) - 1;
            }
        }
        // var_dump($res);
        return $this->returnMsg(200, '查询成功', $data, $count);
    }

    //添加 订单插入
    public function add($data)
    {
        //必填 字段
        $mustField = [
            'orderno',
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'orderno' => '订单编号不能为空',
        ];
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        $isTrue = $this->model->where(['orderno' => $insertData['orderno']])->first();
        // var_dump($isTrue, 4444444444);
        if ($isTrue && !empty($insertData['orders_id'])) {
            $update['orders_id'] = $insertData['orders_id'];
            $isRes = $this->model->where(['orderno' => $insertData['orderno']])->update($update);
            if ($isRes) {
                return $this->returnMsg(200, '提交成功', ['id' => $isTrue->id]);
            }
            return $this->returnMsg(1, '提交失败');
        }
        if (!empty($data['pay_identity'])) {
            // 年龄 性别
            $insertData['sex'] = getIdentitySex($data['pay_identity']);
            $insertData['age'] = getIdentityAge($data['pay_identity']);
        }
        if (empty($insertData['age'])) {
            $insertData['age'] = 0;
        }
        $insertData['time'] = date('H');
        if (!empty($insertData['orders_id'])) {
            $insertData['orders_id_one'] = $insertData['orders_id']; // 区分 第一次 还是最后一次
        }

        // $insertData['shop_str'] = $data['shop_str'];
        if (empty($insertData['created_at'])) {
            $insertData['created_at'] = date('Y-m-d H:i:s');
        }

        if (!empty($insertData['source'])) {
            $insertData['source_type'] = $this->model->getOrderSource($insertData['source']);
        }
        if (empty($insertData['pay_money'])) {
            unset($insertData['pay_money']);
        }
        $res = $this->model->insertGetId($insertData);
        if ($res) {
            return $this->returnMsg(200, '提交成功', ['id' => $res]);
        }
        return $this->returnMsg(1, '提交失败');
    }

//修改旗子
    public function editTagging($postData = [])
    {
        $dealUserId = $postData['user']['id'];
        $tagging = intval($postData['tagging']);
        $where = [];
        if ($postData['user']['shop_id'] != SUPPER_SHOP_ID) {
            $where['eq'] ['shop_id'] = $postData['user']['shop_id'];
        }
        $ordersId = $postData['ordersId'];
        $ordersNo = $postData['ordersNo'];
        $logs = [];
        $tagItem = $this->model->getTaggingItem($tagging);
        if (is_array($ordersNo)) {
            $where['in']['orderno'] = $ordersNo;
            foreach ($ordersId as $k => $v) {
                $logs[] = [
                    'type' => 0,
                    'table_id' => $v,
                    'users_id' => $dealUserId,
                    'created_at' => date('Y-m-d H:i:s'),
                    'content' => '修改订单标旗为:' . $tagItem['name'] ?? $tagging
                ];
            }
        } else {
            $where['eq']['orderno'] = $ordersNo;
            $oldRow = $this->model->searchWhere($where)->select(['id', 'tagging'])->first();
            if ($oldRow->tagging == $tagging) {
                return $this->returnMsg(2, '与旧标识一致,不用修改');
            }
            $logs = [
                'type' => 0,
                'table_id' => $ordersId,
                'users_id' => $dealUserId,
                'created_at' => date('Y-m-d H:i:s'),
                'content' => '修改订单(' . $ordersNo . ')标旗为:' . $tagItem['name'] ?? $tagging
            ];
        }
        $res = $this->model->searchWhere($where)->update(['tagging' => $tagging]);
        if (false !== $res) {
            //            记录操作日志
            $LogsModel = new \App\Models\LogsModel();
            $LogsModel->insert($logs);
        }
        return $this->returnMsg(200, '提交操作成功');
    }

    //修改
    public function edit($where, $data, $isMust = false, $whereOr = [])
    {
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }

        $optionalFields = $this->model->getTableField();
        $field = $this->getRealData($data, [], $optionalFields, []);
        if (isset($field['orderno'])) {
            unset($field['orderno']);
        }
        if (empty($field['tagging'])) {
            unset($field['tagging']);
        }
        $res = $this->model->where($where)->orWhere($whereOr)->update($field);
        if ($res && isset($data['user']['id'])) {
            //            记录操作日志
            $LogsModel = new \App\Models\LogsModel();
            $ordersId = $data['id'] ?? 0;
            $logMsg = "更新了订单备注内容";
            $LogsModel->saveIt(0, $data['user']['id'], $ordersId, $logMsg);
        }
        if ($isMust && $res) {
            return $this->returnMsg(200, '修改成功');
        }
        if (!$isMust) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(3, '请重新修改');
    }

    public function getOne($where, $field = ['*'])
    {
        return $this->model->where($where)->select($field)->first();
    }

    public function getModel()
    {
        return $this->model;
    }

    public function getField()
    {
        return $this->model->getTableField();
    }

    public function getTagging()
    {
        return $this->model->getTagging();
    }
}
